package com.lwm.stream;

import com.lwm.entity.Employee;
import com.lwm.entity.Status;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liweimin
 * @version 1.0
 * @date 2020/9/8 10:21
 */
public class GuiyueAndShoujiTest {
    List<Employee> employeeList = Arrays.asList(
            new Employee("张三", 23, 6433, Status.BUSY),
            new Employee("张三1", 33, 4433, Status.FREE),
            new Employee("张三2", 63, 65333, Status.BUSY),
            new Employee("张三3", 43, 5333, Status.FREE),
            new Employee("张三4", 36, 4233, Status.VACATION)
    );

    @Test
    public void test01() {
        List<Integer> list = Arrays.asList(1, 2, 4, 5, 6, 21, 43, 12, 54, 76);
        System.out.println(list.stream().reduce(0, (x, y) -> x + y));
        Optional<Double> reduce = employeeList.stream().map(Employee::getSalary).reduce(Double::sum);
        System.out.println(reduce.get());
    }

    /**
     * 规约
     */
    @Test
    public void test02() {
        List<String> collect = employeeList.stream().map(Employee::getName).collect(Collectors.toList());
        collect.forEach(System.out::println);
        HashSet<String> collect1 = employeeList.stream().map(Employee::getName).collect(Collectors.toCollection(HashSet::new));
        LinkedHashSet<String> collect2 = employeeList.stream().map(Employee::getName).collect(Collectors.toCollection(LinkedHashSet::new));
    }

    /**
     * 收集
     */
    @Test
    public void test03() {
        Long collect = employeeList.stream().collect(Collectors.counting());
        Double collect1 = employeeList.stream().collect(Collectors.averagingDouble(Employee::getSalary));
        DoubleSummaryStatistics collect2 = employeeList.stream().collect(Collectors.summarizingDouble(Employee::getSalary));
    }

    /**
     * 分组
     */
    @Test
    public void test04() {
        Map<Status, List<Employee>> collect = employeeList.stream().collect(Collectors.groupingBy(Employee::getStatus));
        System.out.println(collect);
        Map<Status, Map<String, List<Employee>>> collect1 = employeeList.stream().collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy(e -> {
            if (e.getAge() >= 60) {
                return "老年";
            } else {
                return e.getAge()>45?"中年":"青年";
            }
        })));
        System.out.println(collect1);
    }

    /**
     * 分区(true/false)
     */
    @Test
    public void test05(){
        Map<Boolean, List<Employee>> map = employeeList.stream().collect(Collectors.partitioningBy(e -> e.getSalary() > 7000));
        System.out.println(map);
    }
}
